package com.yxq.mdt.app.modules.shoppingcart.ui;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.baidu.platform.comapi.map.C;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.application.IntentHelper;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.RouteTable;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.order.ui.OrderConfirmActivity;
import com.yxq.mdt.app.modules.shoppingcart.bean.CartBean;
import com.yxq.mdt.app.modules.shoppingcart.model.CartModel;
import com.yxq.mdt.app.modules.shoppingcart.prestener.CartPresenter;
import com.yxq.mdt.app.modules.shoppingcart.prestener.ICartContract;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 购物车
 */
@Route(path = RouteTable.ROUTER_ACTIVITY_CART)
public class CartActivity extends BaseActivity<CartPresenter> implements ICartContract.View {


    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cart_tv_hint)
    TextView cartTvHint;
    @BindView(R.id.cart_tv_price)
    TextView cartTvPrice;
    @BindView(R.id.cart_tv_submit)
    TextView cartTvSubmit;
    CartListAdapter cartListAdapter;
    @BindView(R.id.cart_check_box_all)
    CheckBox cartCheckBoxAll;
    @BindView(R.id.cart_tv_delete)
    TextView cartTvDelete;
    @BindView(R.id.cart_layout_bottom_edit)
    RelativeLayout cartLayoutBottomEdit;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    boolean enable;

    @Override
    public int getLayoutId() {
        return R.layout.activity_cart;
    }

    @Override
    public void initView() {
        titlebar.setListener((v, action, extra) -> {
            switch (action) {
                case CommonTitleBar.ACTION_LEFT_BUTTON:
                    finish();
                    break;
                case CommonTitleBar.ACTION_RIGHT_TEXT:
                    if (titlebar.getRightTextView().getText().equals("完成")) {
                        titlebar.getRightTextView().setText("编辑");
                        cartLayoutBottomEdit.setVisibility(View.GONE);
                    } else {
                        titlebar.getRightTextView().setText("完成");
                        cartLayoutBottomEdit.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        });
        cartListAdapter = new CartListAdapter(R.layout.layout_cart_item_layout, null);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(cartListAdapter);
        cartListAdapter.setEmptyView(R.layout.layout_empty_shopping_cart_view, recyclerView);
        cartListAdapter.isUseEmpty(false);
        cartListAdapter.setCartCheckedInterface(new CartListAdapter.CartCheckedInterface() {
            @Override
            public void checked(int position) {
                //修改购物车数据
                mPresenter.cartEdit(JSON.toJSONString(cartListAdapter.getData()));
                math();
            }
        });
        cartListAdapter.getEmptyView().findViewById(R.id.empty_btn_go_shopping).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        cartListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.tv_reduce://减少数目
                    int num = cartListAdapter.getData().get(position).getNum();
                    num--;
                    if (num == 0) {
                        num = 1;
                    }
                    cartListAdapter.getData().get(position).setNum(num);
                    cartListAdapter.notifyDataSetChanged();
                    //修改购物车数据
                    mPresenter.cartEdit(JSON.toJSONString(cartListAdapter.getData()));
                    break;
                case R.id.tv_add://增加数目
                    num = cartListAdapter.getData().get(position).getNum();
                    num++;
                    //最大购买数
                    if (num > cartListAdapter.getData().get(position).getMax_num()) {
                        num = cartListAdapter.getData().get(position).getMax_num();
                        ToastUtils.showShort(String.format("该商品最多只能买%d件", num));
                    }
                    cartListAdapter.getData().get(position).setNum(num);
                    cartListAdapter.notifyDataSetChanged();
                    //修改购物车数据
                    mPresenter.cartEdit(JSON.toJSONString(cartListAdapter.getData()));
                    break;
            }
            math();
        });
        cartListAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString("id", cartListAdapter.getItem(position).getGoods_id() + "");
            IntentHelper.arouterUri(RouteTable.ROUTER_ACTIVITY_GOODS_DETAIL, bundle);
        });
        cartCheckBoxAll.setOnCheckedChangeListener((compoundButton, b) -> checkAll(b));
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.cartList());
    }

    /**
     * 全选
     *
     * @param b
     */
    private void checkAll(boolean b) {
        List<CartBean.ListBean> listBeanList = cartListAdapter.getData();
        double allPrice = 0d;
        for (CartBean.ListBean cart : listBeanList) {
            cart.setChecked(b);
            if (b) {
                allPrice += cart.getPrice() * cart.getNum();
            }
        }
        cartListAdapter.notifyDataSetChanged();
        cartTvPrice.setText(String.format("￥%.2f", allPrice));
    }

    /**
     * 计算总价格
     */
    private void math() {
        List<CartBean.ListBean> listBeanList = cartListAdapter.getData();
        double allPrice = 0d;
        for (CartBean.ListBean cart : listBeanList) {
            if (cart.isChecked()) {
                allPrice += cart.getUnitPrice() * cart.getNum();
            }
        }
        cartTvPrice.setText(String.format("￥%.2f", allPrice));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new CartPresenter(this, new CartModel());
        //是否是隐私模式
        enable = Hawk.get(SPKey.SP_KEY_USER_LOGIN_PRIVACY, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }

    @Override
    public void onLoadSuccess(CartBean beanList) {
        refreshLayout.finishRefresh();

        if (!enable && beanList != null && beanList.getList() != null && beanList.getList().size() > 0) {
            cartListAdapter.setNewData(beanList.getList());
            math();
        } else {
            cartListAdapter.isUseEmpty(true);
        }
    }

    @Override
    public void onLoadFailed(String err) {
        refreshLayout.finishRefresh();
        ToastUtils.showShort(err);
    }

    @Override
    public void onDeleteSuccess(List<Integer> position, String msg) {
        for (Integer integer : position) {
            cartListAdapter.remove(integer);
        }
        ToastUtils.showShort(msg);
        math();
        cartListAdapter.isUseEmpty(!(cartListAdapter.getData().size() > 0));
    }

    @Override
    public void onDeleteFailed(String err) {
        ToastUtils.showShort(err);
    }

    @Override
    public void onEditSuccess(String msg) {

    }

    @Override
    public void onEditFailed(String err) {
        ToastUtils.showShort(err);
    }

    @OnClick({R.id.cart_tv_submit, R.id.cart_tv_delete, R.id.cart_layout_bottom_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cart_tv_submit://订单结算
                confirmOrder();
                break;
            case R.id.cart_tv_delete://删除
                showDeleteAlert();
                break;
        }
    }

    /**
     * 跳转结算页面
     */
    private void confirmOrder() {
        List<CartBean.ListBean> listBeanList = cartListAdapter.getData();
        List<CartBean.ListBean> buyGoodsList = new ArrayList<>();
        for (CartBean.ListBean cart : listBeanList) {
            if (cart.isChecked() && cart.getMax_num() > 0) {
                buyGoodsList.add(cart);
            }
        }
        if (buyGoodsList.size() == 0) {
            ToastUtils.showShort("请选择需要购买的商品");
            return;
        }
        Intent intent = new Intent(mActivity, OrderConfirmActivity.class);
        intent.putExtra("from", "cart");//来源 cart：购物车
        intent.putExtra("data", JSON.toJSONString(buyGoodsList));//需要购买的商品数据 Json字符串形式
        startActivity(intent);
    }

    /**
     * 删除购物车中商品提醒框
     */
    private void showDeleteAlert() {
        CostumerDialog dialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_confirm_cancel_layout)
                .setCancelable(true)
                .create();

        TextView title = dialog.findViewById(R.id.tv_title);

        title.setText("");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText("确定删除此商品吗？");

        //继续
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("确定");
        sure.setOnClickListener(v -> {
            dialog.dismiss();
            deleteCartGoods();
        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });

        dialog.show();
    }

    /**
     * 删除购物车中商品
     */
    private void deleteCartGoods() {
        List<CartBean.ListBean> listBeanList = cartListAdapter.getData();
        List<Integer> deleteGoodsIdList = new ArrayList<>();
        List<Integer> deleteGoodsPositionList = new ArrayList<>();
        int i = 0;
        int count = 0;
        for (CartBean.ListBean cart : listBeanList) {
            if (cart.isChecked()) {
                deleteGoodsIdList.add(cart.getCart_id());
                deleteGoodsPositionList.add(i - count);
                count++;
            }
            i++;
        }
        mPresenter.cartDelete(deleteGoodsPositionList, JSON.toJSONString(deleteGoodsIdList));
    }
}
